#include "rt_config.h"


struct Neighbors neighbors;
struct timer_list neighbors_timer;

char neighbors_info[512];
int neighbors_number;

static DEFINE_MUTEX(neighbor_mutex);


int Get_neighbour_info( void* buff )
{
	int j;
	mutex_lock(&neighbor_mutex);
	neighbors_number = 0;
	for (j=1; j<256; j++){
		if (neighbors.node_list[j].ttl>0){
			neighbors_info[neighbors_number*2]=j;
			neighbors_info[neighbors_number*2 +1]=neighbors.node_list[j].rssi;
			neighbors_number++;
		}
	}
	mutex_unlock(&neighbor_mutex);
	
	memcpy(buff,neighbors_info,neighbors_number*2);
	//printk("retrun neighbors length: %d\n", neighbors_number*2);
	return neighbors_number*2;
}



INT Adhoc_add_neighbour(IN CHAR mac[],IN int rssi)
{
    INT j;

	rssi = 0x00ff & rssi;
	//printk("Adhoc_add_neighbour: %d,%d\n",0x00ff & mac[5], 0x00ff & rssi);
	mutex_lock(&neighbor_mutex);
	j = 0x00ff & mac[5];
	if (neighbors.node_list[j].ttl<=0)//a new neighbour
	{
		if (rssi>=185)
		{
			neighbors.number++;
			neighbors.node_list[j].ttl = 5;
		}
	}
	else
	{
       if(rssi>=181)
		  neighbors.node_list[j].ttl = 5;
	}
	neighbors.node_list[j].rssi = rssi;
	mutex_unlock(&neighbor_mutex);
/*
    printk("adhoc beacon from:");
    for(j=0;j<6;j++)
    {
        if( j<5 )
		{
			printk("%02X:",0x000000ff & mac[j]);
        }
        else
		{
        	printk("%02X",0x000000ff & mac[j]);
        }           
    }
	printk(", rssi=%d\n",rssi);
*/
    return TRUE;
 }

 void Adhoc_del_neighbour(unsigned long *arg)
 {
 	int j;

	mutex_lock(&neighbor_mutex);
    //printk("--------------------------------------------------------------Adhoc_del_neighbour N=%d : ", neighbors.number);
	for (j=0; j<256; j++)
	{
		if (neighbors.node_list[j].ttl>0)
		{
			//printk("%d ",j);

			neighbors.node_list[j].ttl--;
			if (neighbors.node_list[j].ttl==0)
			{
				neighbors.number--;
			}
		}
	}
	//printk("\n");
	mutex_unlock(&neighbor_mutex);
	
	mod_timer(&neighbors_timer,jiffies+500); //ms
 }

